<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\adminapi\controller\goods;

use app\common\model\GoodsTag;
use app\common\model\GoodsTagRelation;
use think\facade\Db;
use app\adminapi\controller\Base;
use app\adminapi\validate\goods\TagValidate;

/**
 * Goods tag management
 */
class Tag extends Base
{
    /**
     * Tag list
     */
    public function lists()
    {
        $params = $this->request->params([
            ['keyword', ''],
            ['status', ''],
        ]);

        $list = GoodsTag::withCount('goods')
            ->withSearch($params[0], $params[1])
            ->order('id', 'desc')
            ->paginate($this->limit);

        return $this->success('', [
            'list'  => $list->items(),
            'count' => $list->total()
        ]);
    }

    /**
     * Add tag
     */
    public function add()
    {
        $params = $this->request->post();
        $data   = (new TagValidate())->data('add', $params);
        GoodsTag::create($data);
        return $this->success();
    }

    /**
     * Edit tag
     */
    public function edit()
    {
        $params = $this->request->post();
        $data   = (new TagValidate())->data('edit', $params);

        $tag = GoodsTag::find($data['id']);
        if (!$tag) {
            return $this->error(trans('tag_not_exists'));
        }

        // Check if tag name is duplicate
        if ($tag->name != $params['name']) {
            $exists = GoodsTag::where('name', $params['name'])->find();
            if ($exists) {
                return $this->error(trans('tag_name_exists'));
            }
        }

        $tag->save([
            'name'        => $params['name'],
            'sort'        => $params['sort'] ?? $tag->sort,
            'description' => $params['description'] ?? $tag->description
        ]);

        return $this->success();
    }

    /**
     * Delete tag
     */
    public function delete()
    {
        $id = $this->request->post('id');
        if (!$id) {
            return $this->error(trans('parameter_error'));
        }

        Db::startTrans();
        try {
            // Delete tag
            GoodsTag::destroy($id);
            // Delete tag relations
            GoodsTagRelation::where('tag_id', $id)->delete();

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error();
        }
        return $this->success();
    }

    /**
     * Get all tags (for selection)
     */
    public function all()
    {
        $list = GoodsTag::field('id,name')->order('sort', 'asc')->select();
        // Format label
        $list = $list->toArray();
        $list = array_map(function ($item) {
            return [
                'label' => $item['name'],
                'value' => $item['id']
            ];
        }, $list);
        return $this->success('', $list);
    }

    /**
     * Search tags (for input suggestions)
     */
    public function search()
    {
        $keyword = $this->request->post('keyword', '');
        if (empty($keyword)) {
            return $this->success('', []);
        }

        $tags = GoodsTag::where('name', 'like', '%' . $keyword . '%')
            ->field('name')
            ->limit(10)
            ->select();

        $list = [];
        foreach ($tags as $tag) {
            $list[] = $tag->name;
        }

        return $this->success('', $list);
    }
}